/**
 * 解决数结构 拿最后的id请求ids跟labels
 * @Author: linzy
 * @Date: 2022-06-23
 * @function useTreeValues
 * @param {array} trees - 树结构数组
 * @param {object} fieldNames= { label: 'name', value: 'id', children: 'children' } 字段自定义
 * @returns {object} { trees: cloneTrees, getIds, getNames };
 * @example
 * import { useTreeValues } from "@/hooks";
   const { getIds, getNames } = useTreeValues({ trees: categories });
 */
import { useMemo } from "react";
import _ from "lodash";

export default props => {
  let {
    trees = [],
    fieldNames = { label: "name", value: "id", children: "children" }
  } = props;
  let idObj = {};
  function getIds(id) {
    try {
      const ids = [];
      ids.unshift(idObj[id][fieldNames.value]);
      while (idObj[id].parentId) {
        id = idObj[id].parentId + "";
        ids.unshift(idObj[id][fieldNames.value]);
      }
      return ids;
    } catch (err) {
      return [];
    }
  }
  function getNames(id) {
    try {
      const names = [];
      names.unshift(idObj[id + ""][fieldNames.label]);
      while (idObj[id].parentId) {
        id = idObj[id].parentId + "";
        names.unshift(idObj[id][fieldNames.label]);
      }
      return names;
    } catch (err) {
      return [];
    }
  }
  const result = useMemo(() => {
    if (trees.length === 0) return { trees, getIds, getNames };
    const cloneTrees = _.cloneDeep(trees);
    const arr = [];
    // 递归 在子item写上parentId
    function recursion(list = []) {
      list.forEach(item => {
        if (item[fieldNames.children] && item[fieldNames.children].length > 0) {
          item[fieldNames.children].forEach(cItem => {
            cItem.parentId = item.id;
          });
          recursion(item[fieldNames.children]);
        }
        arr.push(_.omit(item, [fieldNames.children]));
      });
    }
    recursion(cloneTrees);
    idObj = _.keyBy(arr, fieldNames.value);
    return { trees: cloneTrees, getIds, getNames };
  }, [props]);
  return result;
};
